package com.yanqu.road.server.gameplayer.module.activity.jiuzhou;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.jiuzhou.JiuZhouChampionUserData;
import com.yanqu.road.entity.activity.jiuzhou.JiuZhouUserBaseData;
import com.yanqu.road.entity.activity.jiuzhou.config.JiuZhouConfig;
import com.yanqu.road.entity.activity.jiuzhou.config.JiuZhouRoundConfig;
import com.yanqu.road.entity.activity.jiuzhou.config.JiuZhouSkillConfig;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.enums.activity.jiuzhou.eJiuZhouGameZoneType;
import com.yanqu.road.entity.enums.activity.jiuzhou.eJiuZhouRoundType;
import com.yanqu.road.entity.messageSubscribe.entity.MessageUserNoticeData;
import com.yanqu.road.entity.player.UserHistoryAttribute;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.logic.bussiness.activity.JiuZhouBussiness;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.pb.PatronsPb;
import com.yanqu.road.pb.activity.jiuzhou.CrossJiuZhouProto;
import com.yanqu.road.pb.activity.jiuzhou.JiuZhouProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.logic.activity.BaseActivityData;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.douluodalu.DouLuoDaLuMgr;
import com.yanqu.road.server.manger.activity.jiuzhou.JiuZhouMgr;
import com.yanqu.road.logic.pb.JiuZhouPb;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.messagesubscribe.MessageSubscribeMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;

/**
 * 九州棋局
 */
public class JiuZhouModule extends GeneralModule {

    public JiuZhouModule(GamePlayer player) {
        super(player);
    }

    public JiuZhouUserBaseData userBaseData;

    public JiuZhouUserBaseData getUserData() {
        return userBaseData;
    }

    @Override
    public boolean loadData() {
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return false;
        }
        ActivityInfo activityInfo = config.getActivityInfo();
        if (activityInfo == null){
            return false;
        }
        userBaseData = JiuZhouBussiness.getJiuZhouUserBaseData(activityInfo.getActivityId(),getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userBaseData == null){
            return true;
        }
        if (userBaseData.isInsertOption()){
            JiuZhouBussiness.addJiuZhouUserBaseData(userBaseData);
        }else if (userBaseData.isUpdateOption()){
            JiuZhouBussiness.updateJiuZhouUserBaseData(userBaseData);
        }

        return true;
    }

    /**
     * 同步数据
     */
    public void syncData() {
        syncConfig();
        if (!SystemOpenMgr.systemOpen(player, eSystemId.JiuZhou.getValue())) {
            return;
        }
        // todo 有没有必要初始化区服用户数据? 还是直接上跨服拿
        syncUserData();

        // 设置微信推送时间
        try {
            MessageSubscribePushTime();
        }catch (Exception e){
            log.error("error:" + e);
        }
    }

    @Override
    public void afterLogin() {
        syncData();
    }

    /**
     * 设置推送时间
     */
    private void MessageSubscribePushTime(){
        if(!MessageSubscribeMgr.isSwitch()){
            return;
        }
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return;
        }
        ActivityInfo activityInfo = config.getActivityInfo();
        if (activityInfo == null){
            return;
        }

        List<Long> timeApplyList = new ArrayList<>();
        List<Long> timeBattleList = new ArrayList<>();
        Map<Integer, JiuZhouRoundConfig> jiuZhouRoundConfigMap = config.getRoundConfigMap();
        for (JiuZhouRoundConfig roundConfig : jiuZhouRoundConfigMap.values()) {
            if (roundConfig == null) {
                continue;
            }
            List<Integer> jiuZhouTime = roundConfig.getTimeList();
            if (jiuZhouTime.size() <= 3) {
                return;
            }
            int startApplyTime = jiuZhouTime.get(0);
            long applyTime = JiuZhouMgr.getTimeStampAfterBegin(startApplyTime);
            int startBattleTime = jiuZhouTime.get(2);
            long battleTime = JiuZhouMgr.getTimeStampAfterBegin(startBattleTime) - 10 * 60 * DateHelper.SECOND_MILLIONS;
            if (applyTime <= 0 || battleTime <= 0) {
                continue;
            }
            // 报名期提醒要首轮10点
            if (roundConfig.getId() == 1) {
                timeApplyList.add(DateHelper.getZeroTimeStamp(applyTime) + 10 * 60 * 60 * DateHelper.SECOND_MILLIONS);
            }
            timeBattleList.add(battleTime);
        }
        MessageUserNoticeData noticeData = MessageSubscribeMgr.getUserNoticeData(player.getUserId());
        noticeData.setSubTime(eMessageSubscribeType.JiuZhouApplyTime, timeApplyList);
        noticeData.setSubTime(eMessageSubscribeType.JiuZhouBattleTime, timeBattleList);
    }

    /**
     * 获取各个赛区的赚速限制
     */
    public int getZoneAbilityLimit(JiuZhouProto.JiuZhouClientGetAbilityLimitReqMsg reqMsg){
        int activityId = reqMsg.getActivityId();
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        if (config.getActivityId() != activityId){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        player.sendPacket(CrossProtocol.C_JIU_ZHOU_GET_ABILITY_LIMIT, reqMsg.toBuilder());
        return 0;
    }


    /**
     * 用户数据同步
     */
    public void syncUserData() {
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null || !ActivityHelper.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        if (userBaseData == null || userBaseData.getActivityId() !=config.getActivityInfo().getActivityId()){
            initUserBaseData(config.getActivityId());
        }
        if (userBaseData == null) {
            return;
        }
        JiuZhouProto.JiuZhouUserBaseDataMsg.Builder userBaseDataMsg = parseUserBaseDataMsg();
        player.sendPacket(ClientProtocol.U_JIU_ZHOU_BASE_DATA_SYNC, userBaseDataMsg);


        // 上跨服拿个数据
        CrossJiuZhouProto.CrossJiuZhouLoginReqMsg.Builder builder = CrossJiuZhouProto.CrossJiuZhouLoginReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        // 把用户数据带一份上去
        builder.setUserBaseInfo(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
        player.sendPacket(Protocol.C_CROSS_JIU_ZHOU_LOGIN, builder);

        // 登录时，如果已报名了，再把门客上传一下
        if (userBaseData.getHasSignUp() == 1) {
            //先拿出门客上传
            List<UserPatrons> userPatronsList = player.getModule(PatronsModule.class).getUserPatronsList();
            JiuZhouMgr.addPatronsUploadAbility(getUserId(), userPatronsList, true);
        }
    }

    public void initUserBaseData(int activityId){
        if (!SystemOpenMgr.systemOpen(player, eSystemId.JiuZhou.getValue())) {
            return;
        }

        //如果有数据就不初始化了
        if (userBaseData != null && userBaseData.getActivityId() == activityId) {
            return;
        }
        Map<Integer, Map<Integer, Long>> initGuessMap = JiuZhouMgr.getInitGuessMap();
        Map<Integer, Integer> initGuessRewardMap = JiuZhouMgr.getInitGuessRewardMap();
        if (initGuessMap == null || initGuessRewardMap == null) {
            log.error("jiuzhou activityId{} initGuessMap or initGuessRewardMap is null",activityId);
            return;
        }

        JiuZhouUserBaseData tmpUserBaseData = new JiuZhouUserBaseData();
        tmpUserBaseData.setActivityId(activityId);
        tmpUserBaseData.setUserId(getUserId());
        tmpUserBaseData.setHasSignUp(0);
        tmpUserBaseData.setGuessMap(initGuessMap);
        tmpUserBaseData.setGetGuessRewardMap(initGuessRewardMap);
        tmpUserBaseData.setLastWorshipTime(0);
        tmpUserBaseData.setInsertOption();
        userBaseData = tmpUserBaseData;
    }

    /**
     * 配置同步
     */
    public void syncConfig() {
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return;
        }
        JiuZhouProto.JiuZhouConfigSyncMsg.Builder syncMsg = JiuZhouProto.JiuZhouConfigSyncMsg.newBuilder();
        for (JiuZhouRoundConfig roundConfig : config.getRoundConfigMap().values()) {
            syncMsg.addRound(JiuZhouPb.parseJiuZhouRoundConfigMsg(roundConfig));
        }
        for (JiuZhouSkillConfig skillConfig : config.getSkillConfigMap().values()) {
            syncMsg.addSkill(parseJiuZhouSkillConfigMsg(skillConfig, player.getLanguage()));
        }
        player.sendPacket(Protocol.U_JIU_ZHOU_CONFIG_SYNC, syncMsg);
    }

    public static JiuZhouProto.JiuZhouSkillConfigMsg.Builder parseJiuZhouSkillConfigMsg(JiuZhouSkillConfig config,String language) {
        if (config == null) {
            return null;
        }
        JiuZhouProto.JiuZhouSkillConfigMsg.Builder builder = JiuZhouProto.JiuZhouSkillConfigMsg.newBuilder();
        builder.setId(config.getId());
        builder.setName(ServerLanguageMgr.getContent(config.getName(), language));
        builder.setDesc(ServerLanguageMgr.getContent(config.getDesc(), language));
        builder.setType(config.getType());
        builder.setSkillParam(config.getSkillParam());
        builder.setWeight(config.getWeight());
        builder.setItemID(config.getItemID());
        builder.setTag(config.getTag());
        builder.setUseNum(config.getUseNum());
        return builder;
    }

    /**
     * 报名报名
     */
    public int signUp(int activityId){
        if (!SystemOpenMgr.systemOpen(player, eSystemId.JiuZhou.getValue())) {
            return GameErrorCode.E_JIU_ZHOU_NO_UNLOCK;
        }
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        if (config.getActivityId() != activityId){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        if (userBaseData == null || userBaseData.getActivityId() != activityId){
            initUserBaseData(activityId);
        }
        if (userBaseData == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_INIT_DATA_ERROR;
        }
        if (userBaseData.getHasSignUp() == 1){
            return GameErrorCode.E_JIU_ZHOU_HAS_SIGN_UP;
        }

        //拿出玩家当前的评级
        int grade = (int)player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.MonthRankGradeCacheLevel);
        //如果没有评级(可能是还没有同步到) 返回错误码
        if (grade == eMonthRankGradeType.None.getValue()){
            return GameErrorCode.E_JIU_ZHOU_SIGN_NO_REACH_LIMIT;
        }

        int canJoinZoneIdByMonthRankGrade = config.getCanJoinZoneIdByMonthRankGrade(grade);
        if (canJoinZoneIdByMonthRankGrade <= 0){
            return GameErrorCode.E_JIU_ZHOU_SIGN_NO_REACH_LIMIT;
        }

        List<Integer> jiuZhouTime = config.getJiuZhouTime();
        int startSignTime = jiuZhouTime.get(0);
        int endSignTime = jiuZhouTime.get(1);

        long startTimeStamp = JiuZhouMgr.getTimeStampAfterBegin(startSignTime);
        long endTimeStamp = JiuZhouMgr.getTimeStampAfterBegin(endSignTime);

        long now = System.currentTimeMillis();
        //小于开始报名
        if (now < startTimeStamp){
            return GameErrorCode.E_JIU_ZHOU_SIGN_NO_START;
        }
        //大于报名结束
        if (now > endTimeStamp){
            return GameErrorCode.E_JIU_ZHOU_SIGN_END;
        }

        int levelLimit = config.getLevelLimit();
        int patronLimit = config.getSighLimit();
        if (player.getTitleId() < levelLimit){
            return GameErrorCode.E_JIU_ZHOU_SIGN_NO_REACH_LIMIT;
        }
        if (player.getModule(PatronsModule.class).getUserPatronsList().size() < patronLimit){
            return GameErrorCode.E_JIU_ZHOU_SIGN_NO_REACH_LIMIT;
        }



        //拿出历史最高赚速
        UserHistoryAttribute historyAttribute = player.getModule(PlayerModule.class).getUserHistoryAttribute();
        //拿出历史最高门客赚钱
        BigInteger patronsSpeed = historyAttribute.getAbility();


        CrossJiuZhouProto.CrossJiuZhouSignUpReqMsg.Builder builder = CrossJiuZhouProto.CrossJiuZhouSignUpReqMsg.newBuilder();
        builder.setActivityId(activityId);
        builder.setNowMaxAbility(patronsSpeed.toString());
        List<UserPatrons> userPatronsList = player.getModule(PatronsModule.class).getUserPatronsList();
        for (UserPatrons userPatrons : userPatronsList) {
            builder.addPatronsData(PatronsPb.parsePatronsSimpleTempMsg(userPatrons));
        }
        builder.setMonthRankGrade(grade);
        player.sendPacket(CrossProtocol.C_JIU_ZHOU_SIGN_UP, builder);

        return 0;
    }

    /**
     * 每日重置
     */
    public void resetOneDay() {
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return;
        }
        if (userBaseData == null) {
            return;
        }
        if (userBaseData.getSupportRewardTime() == DateHelper.getTodayZeroTimeStamp()) {
            // 今日已获得，这时候不回收
        }
        // 每日回收下声援券
        player.getModule(BagModule.class).recycleItem(config.getMoneyItemId3());
    }

    /**
     * 报名结果返回
     */
    public void signUpResult(JiuZhouProto.SignUpJiuZhouRespMsg resMsg){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            log.error("九州棋局报名成功但游戏服活动不存在");
            return;
        }
        int activityId = config.getActivityId();
        if (resMsg.getRet() != 0){
            return;
        }
        if (userBaseData == null || userBaseData.getActivityId() != activityId){
            initUserBaseData(activityId);
        }
        if (userBaseData == null) {
            log.error("九州棋局id {} ,玩家：{}报名成功但游戏服活动初始化失败",activityId, getUserId());
            return;
        }
        userBaseData.setHasSignUp(1);
        userBaseData.setUpdateOption();
        JiuZhouProto.JiuZhouUserBaseDataMsg.Builder builder = parseUserBaseDataMsg();
        if (builder == null){
            return;
        }
        player.sendPacket(ClientProtocol.U_JIU_ZHOU_BASE_DATA_SYNC, builder);
    }


    /**
     * 主动获取玩家游戏服基础数据
     */
    public int getUserBaseData(int activityId){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        if (config.getActivityId() != activityId){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        if (userBaseData == null || userBaseData.getActivityId() != activityId){
            initUserBaseData(activityId);
        }
        if (userBaseData == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_INIT_DATA_ERROR;
        }
        JiuZhouProto.JiuZhouUserBaseDataMsg.Builder builder = parseUserBaseDataMsg();
        if (builder == null){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_INIT_DATA_ERROR;
        }
        JiuZhouProto.GetBaseJiuZhouUserDataRespMsg.Builder respMsg = JiuZhouProto.GetBaseJiuZhouUserDataRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setBaseData(builder);
        player.sendPacket(ClientProtocol.U_JIU_ZHOU_GET_BASE_DATA, respMsg);
        return 0;
    }


    /**
     * 解析玩家数据成消息
     */
    public JiuZhouProto.JiuZhouUserBaseDataMsg.Builder parseUserBaseDataMsg(){
        if (userBaseData == null){
            return null;
        }
        JiuZhouProto.JiuZhouUserBaseDataMsg.Builder builder = JiuZhouProto.JiuZhouUserBaseDataMsg.newBuilder();
        builder.setHasSignUp(userBaseData.getHasSignUp());
        for (int key:userBaseData.getGetGuessRewardMap().keySet()){
            JiuZhouProto.JiuZhouRewardDataMsg.Builder guessRewardBuild = JiuZhouProto.JiuZhouRewardDataMsg.newBuilder();
            guessRewardBuild.setRoundId(key);
            guessRewardBuild.setRewardState(userBaseData.getGetGuessRewardMap().get(key));
            builder.addRewardData(guessRewardBuild);
        }
        for (Map.Entry<Integer, Map<Integer, Long>> entry: userBaseData.getGuessMap().entrySet()){
            JiuZhouProto.GuessDataMsg.Builder guessDataBuild = JiuZhouProto.GuessDataMsg.newBuilder();
            guessDataBuild.setRoundId(entry.getKey());
            for (Map.Entry<Integer, Long> guessEntry: entry.getValue().entrySet()){
                JiuZhouProto.GuessPlayerDataMsg.Builder guessPlayerBuild = JiuZhouProto.GuessPlayerDataMsg.newBuilder();
                guessPlayerBuild.setRoundType(guessEntry.getKey());
                guessPlayerBuild.setGuessPlayerId(guessEntry.getValue());
                guessDataBuild.addGuessPlayerData(guessPlayerBuild);
            }
            builder.addGuessData(guessDataBuild);
        }
        builder.setLastWorshipTime(userBaseData.getLastWorshipTime());
        return builder;
    }

    /**
     * 竞猜一下   map<赛区，玩家id>
     */
    public int guess(JiuZhouProto.JiuZhouGuessReqMsg reqMsg){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        if (config.getActivityId() != reqMsg.getActivityId()){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        if (userBaseData == null){
            initUserBaseData(config.getActivityId());
        }
        if (userBaseData == null){
            return GameErrorCode.E_JIU_ZHOU_CONFIG_NOT_EXIST;
        }
        //空的不给猜
        if (reqMsg.getGuessDataList().size() == 0 ){
            return GameErrorCode.E_JIU_ZHOU_REQ_PARAM_ERROR;
        }
        //赛区类型数字错误
        for (JiuZhouProto.JiuZhouGuessData jiuZhouGuessData:reqMsg.getGuessDataList()){
            if (eJiuZhouGameZoneType.forValue(jiuZhouGuessData.getZoneType()) == null){
                return GameErrorCode.E_JIU_ZHOU_GAME_ZONE_TYPE_ERROR;
            }
        }

        //竞猜轮次不存在
        if (!config.getRoundConfigMap().containsKey(reqMsg.getRoundId())){
            return GameErrorCode.E_JIU_ZHOU_ROUND_ERROR;
        }
        //已经猜过了 并且是全量猜的
        if (userBaseData.getGuessMap().containsKey(reqMsg.getRoundId())){
            if (userBaseData.getGuessMap().size()==3){
                return GameErrorCode.E_JIU_ZHOU_GUESS_ALREADY;
            }
        }
        //开猜
        player.sendPacket(CrossProtocol.C_JIU_ZHOU_GUESS_TO_CROSS, reqMsg.toBuilder());
        return 0;
    }

    /**
     * 竞猜结果从跨服返回
     */
    public void guessResult(JiuZhouProto.JiuZhouGuessRespMsg respMsg){
        JiuZhouProto.JiuZhouGuessRespMsg.Builder builder = respMsg.toBuilder();
        // 竞猜成功 保存数据
        if (respMsg.getRet() == 0){
            Map<Integer,Long> guessMap = new HashMap<>();
            List<JiuZhouProto.JiuZhouGuessData> guessDataList = respMsg.getGuessDataList();
            guessDataList.forEach(jiuZhouGuessData -> {
                guessMap.put(jiuZhouGuessData.getZoneType(),jiuZhouGuessData.getUserId());
            });
            userBaseData.guess(respMsg.getRoundId(),guessMap);
            builder.setData(parseUserBaseDataMsg());
        }

        player.sendPacket(ClientProtocol.U_JIU_ZHOU_GUESS, builder);
    }



    /**
     * 获取排行榜
     * @param reqMsg
     * @return
     */

    public int getRankList(JiuZhouProto.JiuZhouGetRankReqMsg reqMsg){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        if (config.getActivityId() != reqMsg.getActivityId()){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        player.sendPacket(CrossProtocol.C_JIU_ZHOU_GET_RANK_LIST, reqMsg.toBuilder());
        return 0;
    }

    /**
     * 获取竞猜奖励
     */
    public int getGuessReward(JiuZhouProto.JiuZhouGetGuessRewardReqMsg reqMsg){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        if (config.getActivityId() != reqMsg.getActivityId()){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        if (userBaseData == null){
            initUserBaseData(config.getActivityId());
        }
        if (userBaseData == null){
            return GameErrorCode.E_JIU_ZHOU_CONFIG_NOT_EXIST;
        }

        if (!config.getRoundConfigMap().containsKey(reqMsg.getRoundId())){
            return GameErrorCode.E_JIU_ZHOU_ROUND_ERROR;
        }
        //如果压根就没猜
        if (!userBaseData.getGuessMap().containsKey(reqMsg.getRoundId())){
            return GameErrorCode.E_JIU_ZHOU_NO_GUESS_THIS_ROUND;
        }
        //如果已经领取过奖励了
        if (userBaseData.getGetGuessRewardMap().containsKey(reqMsg.getRoundId()) && userBaseData.getGetGuessRewardMap().get(reqMsg.getRoundId()) == 1){
            return GameErrorCode.E_JIU_ZHOU_GUESS_HAS_GET_REWARD;
        }
        player.sendPacket(CrossProtocol.C_JIU_ZHOU_GET_GUESS_REWARD, reqMsg.toBuilder());
        return 0;
    }

    /**
     * 获取某一轮次的竞猜数据
     * @param reqMsg
     * @return
     */

    public int getRoundGuessData(JiuZhouProto.JiuZhouGetGuessRoundDataReqMsg reqMsg){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        //活动id不对
        if (config.getActivityId() != reqMsg.getActivityId()){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        //竞猜轮次不存在
        if (!config.getRoundConfigMap().containsKey(reqMsg.getRoundId())){
            return GameErrorCode.E_JIU_ZHOU_ROUND_ERROR;
        }
        //如果不是淘汰赛 不能查看
        if (config.getRoundConfigMap().get(reqMsg.getRoundId()).getType() != eJiuZhouRoundType.knockout.getValue()){
            return GameErrorCode.E_JIU_ZHOU_ROUND_ERROR;
        }
        player.sendPacket(CrossProtocol.C_JIU_ZHOU_GET_GUESS_ROUND_DATA, reqMsg.toBuilder());
        return 0;
    }

    /**
     * 获取竞猜正确的玩家列表
     */
    public int getGuessRightPlayerList(JiuZhouProto.JiuZhouGetGuessRightPlayerListReqMsg reqMsg){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        if (config.getActivityId() != reqMsg.getActivityId()){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        //竞猜轮次不存在
        if (!config.getRoundConfigMap().containsKey(reqMsg.getRoundId())){
            return GameErrorCode.E_JIU_ZHOU_ROUND_ERROR;
        }
        //如果不是淘汰赛 不能查看
        if (config.getRoundConfigMap().get(reqMsg.getRoundId()).getType() != eJiuZhouRoundType.knockout.getValue()){
            return GameErrorCode.E_JIU_ZHOU_ROUND_ERROR;
        }
        //如果请求的页数小于0
        if (reqMsg.getPage() < 0){
            return GameErrorCode.E_JIU_ZHOU_REQ_PARAM_ERROR;
        }
        //如果请求的正确数量超过了最大值 或者 小于0
        if (reqMsg.getRightNum() < 0 || reqMsg.getRightNum() > 3){
            return GameErrorCode.E_JIU_ZHOU_REQ_PARAM_ERROR;
        }
        player.sendPacket(CrossProtocol.C_JIU_ZHOU_GET_GUESS_RIGHT_USER_LIST, reqMsg.toBuilder());
        return 0;
    }

    /**
     * 声援
     *
     * @return
     */
    public int support(int activityId) {
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        if (config.getActivityId() != activityId) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
        Property property = new Property(config.getMoneyItemId3(), BigInteger.ONE);
        if(!currencyModule.currencyIsEnough(property)){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        // 预扣除
        player.getModule(PreReduceModule.class).preReduce(property);

        // 上跨服
        CrossJiuZhouProto.CrossJiuZhouSupportReqMsg.Builder builder = CrossJiuZhouProto.CrossJiuZhouSupportReqMsg.newBuilder();
        builder.setActivityId(activityId);
        player.sendPacket(CrossProtocol.C_CROSS_JIU_ZHOU_SUPPORT, builder);
        return 0;
    }

    /**
     * 跨服返回竞猜正确的玩家列表
     * @param respMsg
     */

    public void getGuessRewardFromCross(JiuZhouProto.JiuZhouGetGuessRewardRespMsg respMsg){
        JiuZhouProto.JiuZhouGetGuessRewardRespMsg.Builder builder = respMsg.toBuilder();
        if (respMsg.getRet()!=0){
            player.sendPacket(ClientProtocol.U_JIU_ZHOU_GET_GUESS_REWARD, builder);
        }
        int roundId = respMsg.getRoundId();
        int rightNum = respMsg.getRightNum();
        //如果这个轮次已经领过奖励了 返回错误码
        if (userBaseData.hasGetGuessReward(roundId)){
            builder.setRet(GameErrorCode.E_JIU_ZHOU_GUESS_HAS_GET_REWARD);
            player.sendPacket(ClientProtocol.U_JIU_ZHOU_GET_GUESS_REWARD, builder);
            return;
        }
        //如果这个轮次没有猜过 返回错误码
        if (!userBaseData.getGuessMap().containsKey(roundId)){
            builder.setRet(GameErrorCode.E_JIU_ZHOU_NO_GUESS_THIS_ROUND);
            player.sendPacket(ClientProtocol.U_JIU_ZHOU_GET_GUESS_REWARD, builder);
            return;
        }
        //拿出奖励
        Property guessRewardByRightNum = JiuZhouMgr.getGuessRewardByRightNum(roundId, rightNum);
        if (guessRewardByRightNum == null){
            builder.setRet(GameErrorCode.E_JIU_ZHOU_CONFIG_NOT_EXIST);
            player.sendPacket(ClientProtocol.U_JIU_ZHOU_GET_GUESS_REWARD, builder);
            return;
        }
        //发奖励 先设置领取状态再发
        userBaseData.getGuessReward(roundId);
        player.getModule(CurrencyModule.class).addCurrency(guessRewardByRightNum, eLogMoneyType.JiuZhou, eLogMoneyType.JiuZhouGetGuessReward);
        builder.setReward(PropertyHelper.parsePropertyToString(guessRewardByRightNum));
        builder.setData(parseUserBaseDataMsg());
        player.sendPacket(ClientProtocol.U_JIU_ZHOU_GET_GUESS_REWARD, builder);
        return;
    }

    /**
     * 获取历届冠军数据
     * @param activityId
     * @return
     */

    public int getChampionData(int activityId){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        //活动id不对
        if (config.getActivityId() != activityId){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        List<JiuZhouProto.JiuZhouActivityChampionDataMsg> historyChampion = JiuZhouMgr.getHistoryChampionMsg(activityId);
        if (historyChampion == null){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_DATA_PREPARING;
        }
        JiuZhouProto.JiuZhouGetChampionDataRespMsg.Builder builder = JiuZhouProto.JiuZhouGetChampionDataRespMsg.newBuilder();
        builder.setRet(0);
        builder.addAllChampionData(historyChampion);
        player.sendPacket(ClientProtocol.U_JIU_ZHOU_GET_CHAMPION_DATA, builder);
        return 0;
    }

    /**
     * 获取淘汰赛所有赛区的房间信息
     */
    public int getOutRoundRoomData(JiuZhouProto.JiuZhouGetOutRoundRoomDataReqMsg reqMsg){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        //活动id不对
        if (config.getActivityId() != reqMsg.getActivityId()){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        JiuZhouRoundConfig roundConfig = JiuZhouMgr.getRoundConfig(reqMsg.getActivityId(), reqMsg.getRoundId());
        if (roundConfig == null){
            return GameErrorCode.E_JIU_ZHOU_ROUND_ERROR;
        }
        if (roundConfig.getType() != eJiuZhouRoundType.knockout.getValue()){
            return GameErrorCode.E_JIU_ZHOU_ROUND_ERROR;
        }
        player.sendPacket(CrossProtocol.C_JIU_ZHOU_GET_OUT_ROUND_DATA, reqMsg.toBuilder());
        return 0;
    }

    /**
     * 膜拜冠军
     */
    public int worshipChampion(int activityId){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        //活动id不对
        if (config.getActivityId() != activityId){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        if (userBaseData == null){
            initUserBaseData(config.getActivityId());
        }
        if (userBaseData == null){
            return GameErrorCode.E_JIU_ZHOU_CONFIG_NOT_EXIST;
        }

        JiuZhouChampionUserData championUserData = JiuZhouMgr.getChampionUserData(activityId, eJiuZhouGameZoneType.king.getValue());
        if (championUserData == null){
            return GameErrorCode.E_JIU_ZHOU_WORSHIP_CHAMPION_NO_EXIST;
        }
        long now = System.currentTimeMillis();
        long lastWorshipTime = userBaseData.getLastWorshipTime();
        if (lastWorshipTime > 0){
            //判断是否是同一天
            if (DateHelper.isSameDay(lastWorshipTime /1000, now /1000)){
                return GameErrorCode.E_JIU_ZHOU_WORSHIP_CHAMPION_HAS_WORSHIP;
            }
        }
        Property randomWorshipReward = JiuZhouMgr.getRandomWorshipReward(activityId);
        if (randomWorshipReward == null){
            return GameErrorCode.E_JIU_ZHOU_CONFIG_NOT_EXIST;
        }
        userBaseData.setLastWorshipTime(now);

        player.getModule(CurrencyModule.class).addCurrency(randomWorshipReward, eLogMoneyType.JiuZhou, eLogMoneyType.JiuZhouWorshipChampionReward);

        JiuZhouProto.JiuZhouWorshipChampionRespMsg.Builder builder = JiuZhouProto.JiuZhouWorshipChampionRespMsg.newBuilder();
        builder.setRet(0);
        builder.setReward(PropertyHelper.parsePropertyToString(randomWorshipReward));
        builder.setLastWorshipTime(now);
        player.sendPacket(ClientProtocol.U_JIU_ZHOU_WORSHIP_CHAMPION, builder);
        return 0;
    }

    public int getRankReward(JiuZhouProto.JiuZhouGetRankRewardReqMsg reqMsg){
        JiuZhouConfig config = JiuZhouMgr.getConfig();
        if (config == null || !ActivityHelper.activityInShowTime(config.getActivityInfo())){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
        }
        //活动id不对
        int activityId = reqMsg.getActivityId();
        if (config.getActivityId() != activityId){
            return GameErrorCode.E_JIU_ZHOU_ACTIVITY_ID_ERROR;
        }
        if (!ActivityMgr.activityInCanRewardPeriod(config.getActivityInfo())) {
            return GameErrorCode.E_JIU_ZHOU_NO_IN_REWARD_TIME;
        }
        int conditionId = reqMsg.getConditionId();

        // 是否有活动数据
        BaseActivityData baseActivityData = player.getModule(ActivityModule.class).getBaseActivityData(activityId);
        if (baseActivityData == null) {
            return GameErrorCode.E_ACTIVITY_CONDITION_NO_COMPLETE;
        }

        ActivityConditionInfo activityConditionInfo = NormalActivityMgr.getActivityConditionInfo(activityId, conditionId);
        if(null == activityConditionInfo){
            return GameErrorCode.E_ACTIVITY_GET_REWARD_CONDITION_ERROR;
        }
        UserActivityConditionData userActivityConditionData = baseActivityData.getUserActivityConditionData(conditionId);

        if(null == userActivityConditionData){
            return GameErrorCode.E_ACTIVITY_NO_JOIN;
        }

        if (userActivityConditionData.isGetReward()) {
            return GameErrorCode.E_ACTIVITY_REWARD_IS_GET;
        }

        //上跨服吧
        player.sendPacket(CrossProtocol.C_CROSS_JIU_ZHOU_GET_RANK_REWARD, reqMsg.toBuilder());
        return 0;
    }

    public void getUserMonthRankGrade(){
        int attribute = (int) player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.MonthRankGradeCacheLevel);
        JiuZhouProto.JiuZhouGetUserMonthRankRespMsg.Builder builder = JiuZhouProto.JiuZhouGetUserMonthRankRespMsg.newBuilder();

        builder.setGrade(attribute);
        player.sendPacket(ClientProtocol.U_JIU_ZHOU_GET_USER_MONTH_RANK_GRADE,builder);
    }




}
